import { NotifyService } from '@abp/notify/notify.service';
import { Component, Injector, ViewChild, ViewEncapsulation, OnInit, Inject, Optional, InjectionToken } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { ActivatedRoute } from '@angular/router';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table, TableCheckbox } from 'primeng/components/table/table';
import { Http } from '@angular/http';
import { EntityDtoOfInt64, TokenAuthServiceProxy, SFOrderListDto, SFOrderServiceProxy } from '@shared/service-proxies/service-proxies';
import { FileUploader, FileUploaderOptions, FileItem } from 'ng2-file-upload';
import { IAjaxResponse } from '@abp/abpHttpInterceptor';
import { TokenService } from '@abp/auth/token.service';
import { Observable, from as _observableFrom, throwError as _observableThrow, of as _observableOf } from 'rxjs';
export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');
import { HttpClient, HttpParams, HttpHeaders, HttpResponse, HttpResponseBase } from '@angular/common/http';
import { PrintModalComponent } from './print-modal/print-modal.component';
import { OrderinfoComponent } from './orderinfo/orderinfo.component';
import { Action } from 'rxjs/internal/scheduler/Action';





@Component({
  selector: 'app-sforder',
  templateUrl: './sforder.component.html',
  styleUrls: ['./sforder.component.css'],
  encapsulation: ViewEncapsulation.None,
  animations: [appModuleAnimation()]
})
export class SforderComponent extends AppComponentBase implements OnInit {
  @ViewChild('printImgModal') printModal: PrintModalComponent;
  @ViewChild('orderinfoModal') orderinfoModal: OrderinfoComponent;
  @ViewChild('dataTable') dataTable: Table;
  @ViewChild('paginator') paginator: Paginator;
  @ViewChild('tableCheckbox') checkbox: TableCheckbox;
  //Filters
  serviceStationCode = '';
  serviceStationName = '';
  excelUploader: FileUploader;
  advancedFiltersAreShown = false;
  filterText = '';
  selectedPermission = '';
  role: number = undefined;
  onlyLockedUsers = false;

  public ids: Array<number> = new Array<number>();
  datas = [];

  private http: HttpClient;
  private baseUrl: string;
  protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

  constructor(
    injector: Injector,
    private _http: Http,
    public _sfOrderServiceProxy: SFOrderServiceProxy,
    private _notifyService: NotifyService,
    private _tokenAuth: TokenAuthServiceProxy,
    private _activatedRoute: ActivatedRoute,
    private _tokenService: TokenService,
    @Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string
  ) {
    super(injector);
    this.http = http;
  }

  ngOnInit(): void {

    this.initUploaders();
  }

  initUploaders(): void {
    this.excelUploader = this.createUploader(
      '/SFOrder/ImportFromExcel?v=' + Date.now(),
      result => {
        this.appSession.tenant.logoFileType = result.fileType;
        this.appSession.tenant.logoId = result.id;
      }
    );




  }

  createUploader(url: string, success?: (result: any) => void): FileUploader {
    const uploader = new FileUploader({ url: AppConsts.remoteServiceBaseUrl + url });

    uploader.onAfterAddingFile = (file) => {
      file.withCredentials = false;
      //uploader.uploadAll();

    };

    uploader.onSuccessItem = (item, response, status) => {
      const ajaxResponse = <IAjaxResponse>JSON.parse(response);
      if (ajaxResponse.success) {
        this.notify.info(this.l('SavedSuccessfully'));
        if (success) {
          this.getPageList();
          success(ajaxResponse.result);
        }
      } else {
        this.message.error(ajaxResponse.error.message);
      }

    };

    const uploaderOptions: FileUploaderOptions = {};
    uploaderOptions.authToken = 'Bearer ' + this._tokenService.getToken();
    uploaderOptions.removeAfterUpload = true;
    uploaderOptions.autoUpload = true;
    uploaderOptions.allowedFileType = ['xlsx', 'xls'];
    uploader.setOptions(uploaderOptions);
    return uploader;
  }

  getPageList(event?: LazyLoadEvent) {
    if (this.primengTableHelper.shouldResetPaging(event)) {
      this.paginator.changePage(0);

      return;
    }

    this.primengTableHelper.showLoadingIndicator();

    this._sfOrderServiceProxy.getPageListAsync(
      this.serviceStationCode,
      this.serviceStationName,
      this.primengTableHelper.getSorting(this.dataTable),
      this.primengTableHelper.getMaxResultCount(this.paginator, event),
      this.primengTableHelper.getSkipCount(this.paginator, event)
    ).subscribe(result => {
      this.primengTableHelper.totalRecordsCount = result.totalCount;
      this.primengTableHelper.records = result.items;
      this.primengTableHelper.hideLoadingIndicator();
    });
  }

  importExcel(): void {
  }
  reloadPage(): void {
    this.paginator.changePage(this.paginator.getPage());
  }
  delete(rec: SFOrderListDto): void {

    this.message.confirm(
      rec.id + '',
      '确定删除吗',
      (isConfirmed) => {
        if (isConfirmed) {
          this._sfOrderServiceProxy.deleteAsync(rec.id)
            .subscribe(() => {
              this.reloadPage();
              this.notify.success(this.l('SuccessfullyDeleted'));
            });
        }
      }
    );

  }

  oneprint(id: number): void {
    this._sfOrderServiceProxy.getPrintJson(id)
      .subscribe((ref) => {


        let options_: any = {
          observe: 'response',
          //body: JSON.stringify({ 'json': ref }),
          responseType: 'blob',
          headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'http-equiv': 'Content-Security-Policy',
            'content': 'upgrade-insecure-requests'
          })
        };
        let ss = {
          params: new HttpParams().set('json', ref)
        };
        console.log(ref);

        this.http.post(AppConsts.printUrl, { 'json': ref }, options_).subscribe(data => {
          console.log(data);



        });
      }, (error) => {

      });
  }
  bachPrint(): void {
    console.log(this.ids);
    for (let num = 0; num < this.ids.length; num++) {
      let id = this.ids[num];
      this.oneprint(id);
    }
    this.ids.forEach(function (id, val) {       //遍历表格数据的列表项
      // this.oneprint(id);
      //this.isSelected(id);
    });

  }

  // 全选
  checkAll(e) {
    let checked = e.target.checked;  //判断全选按钮是否被选中
    console.log('aa');

    if (checked) {
      this.primengTableHelper.records.forEach(function (key, val) {       //遍历表格数据的列表项
        // this.ids = [0, 0];
        this.ids.push(key.id);                        //选择那一列所有的都会被选中
      });
    }
  }
  checkboxClick(e, id: number, s: boolean): void {


    let checked = e.target.checked;
    console.log(checked);
    let action = 'add';
    if (!checked) {
      action = 'remove';
    }
    this.updateSelected(action, id);
  }

  updateSelected(action: string, id: number): void {
    if (action === 'add' && this.ids.indexOf(id) === -1) {
      this.ids.push(id);
    }
    if (action === 'remove' && this.ids.indexOf(id) !== -1) {
      this.ids.splice(this.ids.indexOf(id), 1);
    }
    console.log(this.ids);
  }

  //更新某一列数据的选择
  updateSelection($event, id: number): void {
    console.log('updateSelection');

    let checked = $event.target.checked;
    let action = (checked ? 'add' : 'remove');
    this.updateSelected(action, id);
  }
  //全选操作
  selectAll($event) {
    let checkbox = $event.target;
    let action = (checkbox.checked ? 'add' : 'remove');
    for (let i = 0; i < this.primengTableHelper.records.length; i++) {
      let contact = this.primengTableHelper.records[i];
      this.updateSelected(action, contact.id);
    }
  }
  isSelected(id: number): boolean {
    return this.ids.indexOf(id) >= 0;
  }

  isSelectedAll(): boolean {
    console.log(11);
    return this.ids.length === this.primengTableHelper.records.length;
  }
}
